package com.briup.day31;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * @author ThinkBook
 */
public class TestField {
    public static void main(String[] args) throws Exception{
        Class<Student> studentClass = Student.class;
        // getFields获取类中所有的public修饰的属性（包括从父类继承的）
        Field[] fields = studentClass.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("---------------------------------");
        // getDeclaredFields获取类中所有的属性（包括私有的，不包括父类继承的）
        Field[] declaredFields = studentClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
        System.out.println("---------------------------------");
        // getField(String name)：根据属性的名称获取属性，只能public修饰的属性（包括从父类继承的）
        Field id = studentClass.getField("id");
        System.out.println(id);

        Field address = studentClass.getField("address");
        System.out.println(address);
        // getDeclaredField(String name)：根据属性的名称获取属性，访问本类的所有属性（不包括继承的属性）
        Field name = studentClass.getDeclaredField("name");
        System.out.println(name);
        Field age = studentClass.getDeclaredField("age");
        System.out.println(age);
        // Field address1 = studentClass.getDeclaredField("address");
        // System.out.println(address1);
        System.out.println("---------------------------------");
        Constructor<Student> constructor = studentClass.getConstructor();
        Student student = constructor.newInstance();
        System.out.println(student);
        // set(Object obj, Object value) obj:要赋值的对象，value:要赋值的属性值
        id.set(student, "1001");
        System.out.println(student);

        name.set(student, "zhangsan");
        System.out.println(student);

        // 如果要为private修饰的成员变量赋值，需要放开权限（setAccessible）
        age.setAccessible(true);
        age.set(student, 20);
        System.out.println(student);

        int o = (int) age.get(student);
        System.out.println(o);
    }
}
